<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>08_综合案例</title>
    <style>
        #app{
            margin: 0 auto;
            width: 500px;
        }
        table {
            border-collapse: collapse;
        }

        table,
        th,
        td {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <div id="app">
        <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>名称</th>
                    <th>数量</th>
                    <th>价格</th>
                </tr>
            </thead>

            <tbody>
                <tr v-for="(book,index) in books">
                    <td>{{book.id}}</td>
                    <td>{{book.name}}</td>
                    <td>
                        <button v-on:click="increment(index)">+</button>
                        {{book.number}}
                        <button v-on:click="decrement(index)">-</button>
                    </td>
                    <td>{{book.price}}</td>
                    <td>
                        <button v-on:click="removeBook(index)">移除</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <p>总价: {{totalPrice}}</p>
    </div>
</body>
<script src="../vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            books: [
                {"id":1,"name":"西游记","number":1,"price":50},
                {"id":2,"name":"水浒传","number":1,"price":60},
                {"id":3,"name":"红楼梦","number":1,"price":70},
                {"id":4,"name":"三国演义","number":1,"price":80},
            ],
        },
        methods: {
            increment(index){
                this.books[index].number++
            },
            decrement(index){
                if(this.books[index].number <= 1){
                    return
                }
                this.books[index].number--
            },
            removeBook(index){
                this.books.splice(index, 1)
            }
        },
        computed: {
            totalPrice(){
                let totalPrices = 0
                for(let i in this.books){
                    totalPrices += this.books[i].price * this.books[i].number
                }
                return totalPrices
            }
        }
    })
</script>
</html>